package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.dao.HomeMapper;
import com.drd.dt.modular.dao.UserMapper;
import com.drd.dt.modular.dto.*;
import com.drd.dt.modular.entity.*;
import com.drd.dt.modular.service.HomeService;
import com.drd.dt.modular.service.PDDService;
import com.drd.dt.modular.service.WphService;
import com.drd.dt.properties.HDKPropertyConfig;
import com.drd.dt.properties.TBLMPropertyConfig;
import com.drd.dt.util.HttpConnectionPoolUtil;
import com.drd.dt.util.JedisClient;
import com.drd.dt.util.ResultUtil;
import com.drd.dt.util.StringUtil;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkSpreadGetRequest;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.response.TbkSpreadGetResponse;
import com.taobao.api.response.TbkTpwdCreateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by 86514 on 2019/3/25.
 */
@Service
@Transactional
public class HomeServiceImpl implements HomeService {
    @Autowired
    private UserMoneyServiceImpl testMoneyService;

    @Autowired
    private HomeMapper homeMapper;
    @Autowired
    private HDKPropertyConfig hdkPropertyConfig;
    @Autowired
    private TBLMPropertyConfig tblmPropertyConfig;
    @Autowired
    private JedisClient jedisClient;
    @Autowired
    private TBGoodsServiceImpl tbGoodsService;
    @Autowired
    private PDDService pddService;
    @Autowired
    private WphService wphService;
    @Autowired
    private UserMoneyServiceImpl moneyService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 首页请求数据合集
     **/
    @Override
    public Tip list(String user_id) throws Exception {
        JSONObject result = new JSONObject();
        //获取首页菜单分类
        List<Mall> category = selectCategory();
        //获取首页公告活动列表
        List<ActivityDTO> notice = selectNotice();
        //获取首页底部提现滚动信息
        List<RollMSGDTO> rollList = selectRollList(user_id);
        //获取首页消息红点提示(是否已读（0否；1是）)
        Integer read_status = readStatus(user_id);
        result.put("category", category);
        result.put("notice", notice);
        result.put("roll", rollList);
        result.put("is_read", read_status);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 获取首页消息红点提示
     */
    private Integer readStatus(String user_id) throws Exception {
        Integer is_read = 0;
        if (!StringUtils.isEmpty(user_id)) {
            Integer count = homeMapper.getReadStatus(user_id);
            //是否已读（0否；1是）
            if (null != count && count < 1) {
                return 1;//已读
            }
        }
        return is_read;
    }

    /**
     * 获取首页菜单分类
     */
    private List<Mall> selectCategory() throws Exception {
        List<Mall> list = homeMapper.selectCategory();
        return list;
    }

    /**
     * 获取首页公告活动列表
     */
    private List<ActivityDTO> selectNotice() throws Exception {
        List<ActivityDTO> list = homeMapper.selectNotice();
        return list;
    }

    /**
     * 获取首页底部滚动信息
     */
    private List<RollMSGDTO> selectRollList(String user_id) throws Exception {
        List<RollMSGDTO> result = new ArrayList<>();
        List<RollMSGDTO> txList = homeMapper.getSYSShowList(user_id);//系统消息
        //根据type拼接系统消息的内容
        //0 全局系统  1,自己注册 2,邀请粉丝成功，有新粉丝注册  3,自己VIP升级 4提现的
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat y_m_d_h_m_s = Constant.y_M_d_H_m_s;
        txList.stream().forEach(t -> {
            Integer type = t.getType();
            String nick_name = t.getNick_name();
            Integer mType = 0;
            if (type == 3) {//自己VIP升级
                try {
                    mType = 4;
                    cal.setTime(y_m_d_h_m_s.parse(t.getCreate_time()));
                    cal.add(Calendar.YEAR, 1);
                    t.setCreate_time(y_m_d_h_m_s.format(cal.getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (type == 1) {//自己注册
                nick_name = "";
            }
            if (type != 0){
                String messageText = moneyService.getMessageText(nick_name, t.getCreate_time(), "", mType);
                t.setContent(messageText);
            }
        });

        result.addAll(txList);
        if (!StringUtils.isEmpty(user_id)) {//用户id不为空时获取佣金消息
            List<RollMSGDTO> commissionList = homeMapper.getcommissionList(user_id);//佣金消息
            if (null != commissionList) {
                commissionList.stream().forEach(t -> {
                    //佣金类型 1直接销售收益，2粉丝收益，3奖励收益 ，4退款扣除
                    Integer message_type = t.getMessage_type();
                    String rake_money = t.getRake_money();
                    String create_time = t.getCreate_time();
                    RollMSGDTO rollMSGDTO = new RollMSGDTO();
                    String msg = "";
                    if (message_type == 1) {
                        rollMSGDTO.setTitle(Constant.SYS_COMISSION);
                        msg = "普通预估佣金";
                    } else if (message_type == 3) {
                        rollMSGDTO.setTitle(Constant.SYS_BOUNTY);
                        msg = "奖励佣金";
                    }
                    rollMSGDTO.setContent(" 您有一笔" + msg + rake_money + "元成功入账，请到消息中心查看详情");
                    rollMSGDTO.setCreate_time(create_time);
                    result.add(rollMSGDTO);
                });
            }
        }
        StringBuilder resultContent = new StringBuilder();//将content内容拼接为一条，方便前端展示
        final Integer[] flag = {0};
        result.stream().forEach(t -> {
            String content = t.getContent();
            if (!StringUtils.isEmpty(content)) {
                if (flag[0] == 0) {
                    resultContent.append(content);
                } else {
                    resultContent.append("  " + content);
                }
            }
            flag[0]++;
        });
        result.clear();
        RollMSGDTO dto = new RollMSGDTO();
        dto.setContent(String.valueOf(resultContent));
        result.add(dto);
        return result;
    }

    /**
     * 获取开屏或banner图
     **/
    public Tip getAds(Integer block,String imei,HttpServletRequest request, String deviceT, String app_version) throws Exception {
        JSONObject result = new JSONObject();
        JSONArray openScreen = new JSONArray();
        JSONArray homeBanner = new JSONArray();
        JSONArray gif = new JSONArray();
        JSONArray sign = new JSONArray();
        JSONArray floatImg = new JSONArray();
        JSONArray personal = new JSONArray();
        JSONArray activity = new JSONArray();
        JSONArray activity_bg = new JSONArray();
        JSONArray insertScreen = new JSONArray();
        String time = Constant.y_M_d.format(new Date());
        Object value = jedisClient.get("htsq:adv:"+ imei);
        Integer a_version = 0;
        if (!StringUtils.isEmpty(app_version) && app_version.contains(".")){
            a_version = Integer.valueOf(app_version.replaceAll("\\.",""));
        }
        Integer is_read = 0;
        String rTime ;
        if (null != value){
            rTime = String.valueOf(value);
            if (!StringUtils.isEmpty(rTime) && rTime.equals(time)){//今天已看过插屏
                is_read = 1;
            }else {
                if (!StringUtils.isEmpty(imei)){
                    jedisClient.setWithExpire("htsq:adv:"+ imei, time, 60 * 60 * 24);
                }
            }
        }else {//redis没有时
            if (!StringUtils.isEmpty(imei)){
                jedisClient.setWithExpire("htsq:adv:"+ imei, time, 60 * 60 * 24);
            }
        }
        List<Adv> list = homeMapper.getAds(block);
        //判断是否为国外ip
        String ip = StringUtil.getIpAddr(request);
        String country = new StringUtil().getIPLocation(ip);
        String version = userMapper.getVerifyVersion();//获取ios审核版本号
        Integer finalIs_read = is_read;
        Integer finalA_version = a_version;
        list.stream().forEach(t -> {
            Integer blockType = t.getBlock();
            //1首页banner 2开屏 3首页gif 4签到 5浮图 6个人中心banner 7活动专区 8首页活动区背景图 9插屏
            switch (blockType) {
                case 1:
                    homeBanner.add(t);
                    break;
                case 2:
                    openScreen.add(t);
                    break;
                case 3:
                    gif.add(t);
                    break;
                case 4:
                    sign.add(t);
                    break;
                case 5:
                    if (!app_version.equals(version) && !country.equals("美国")){
                        if (StringUtils.isEmpty(deviceT) || deviceT.equals("0") || (deviceT.equals("1") && finalA_version > 204)){
                            floatImg.add(t);
                        }
                    }
                    break;
                case 6:
                    personal.add(t);
                    break;
                case 7:
                    activity.add(t);
                    break;
                case 8:
                    activity_bg.add(t);
                    break;
                case 9:
                    if (finalIs_read == 0 && !app_version.equals(version) && !country.equals("美国")){
                        insertScreen.add(t);
                    }
                    break;
            }
        });
        result.put("homeBanner", homeBanner);
        result.put("openScreen", openScreen);
        result.put("gif", gif);
        result.put("sign", sign);
        result.put("floatImg", floatImg);
        result.put("personal", personal);
        result.put("activity", activity);
        result.put("activityBG", activity_bg);
        result.put("insertScreen", insertScreen);

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 限时秒杀时间点
     **/
    @Override
    public Tip seckillTime() throws Exception {
        JSONObject result = new JSONObject();
        List<SeckillTimeDTO> seckills = homeMapper.selectSeckillTime();
        SimpleDateFormat H_m_s = Constant.H_m_s;
        SimpleDateFormat y_M_d_H_m_s = Constant.y_M_d_H_m_s;
        SimpleDateFormat y_M_d = Constant.y_M_d;
        Date date = new Date();
        String format = H_m_s.format(date);
        Date now = H_m_s.parse(format);
        SimpleDateFormat H_m = Constant.H_m;
        final Integer[] flag = {0};
        final Long[] sec = {0L};
        final Integer[] sequence = {0};
        final Integer[] type = new Integer[1];
        String StrYMD = y_M_d.format(date);
        Date lastTime = y_M_d_H_m_s.parse(StrYMD + " " + seckills.get(seckills.size() - 1).getSeckill_time());//最后一个秒杀时间
        if (date.getTime() >= lastTime.getTime()) {
            sequence[0] = seckills.get(seckills.size() - 1).getSequence();
            type[0] = seckills.get(seckills.size() - 1).getType();
            Date firstTime = y_M_d_H_m_s.parse(StrYMD + " " + seckills.get(0).getSeckill_time());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(firstTime);
            int day = calendar.get(Calendar.DATE);
            calendar.set(Calendar.DATE, day + 1);
            sec[0] = calendar.getTime().getTime() - date.getTime();
        }
        seckills.stream().forEach(t -> {
            String seckill_time = t.getSeckill_time();
            try {
                Date seckill = H_m_s.parse(seckill_time);
                if (seckill.getTime() >= now.getTime()) {//大于等于现在时间（即将开始）
                    if (flag[0] == 0) {
                        sequence[0] = t.getSequence() - 1;//获取抢购中的时间点
                        sec[0] = (seckill.getTime() - now.getTime());
                        type[0] = t.getType();
                    }
                    t.setDesc(Constant.INSTANTLY_OPEN);
                    flag[0]++;
                } else {
                    t.setDesc(Constant.IS_OPENED);
                }
                t.setSeckill_time(H_m.format(seckill));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
        seckills.stream().filter(t -> t.getSequence() == sequence[0]).forEach(p -> p.setDesc(Constant.IS_OPENING));
        result.put("seckillGoods", seckills);
        result.put("seckillTime", sec[0]);
        result.put("type", type[0]);
        result.put("seckillDesc", Constant.SECKILL_DESC);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 限时秒杀商品列表
     **/
    @Override
    public Tip seckillGoods(String page, String type, Integer user_id) throws Exception {
        if (StringUtils.isEmpty(type)) {
            type = "7";
        }
        JSONArray result = new JSONArray();
        String apiKey = hdkPropertyConfig.getApiKey();
        String hdk_url = hdkPropertyConfig.getFastbuyUrl() + "apikey/" + apiKey + "/hour_type/" + type + "/min_id/" + page;
        String dataStr = HttpConnectionPoolUtil.get(hdk_url);
        if (!StringUtils.isEmpty(dataStr)) {
            JSONObject dataJson = JSON.parseObject(dataStr);
            Integer code = dataJson.getInteger("code");
            if (code == 1) {
                JSONArray datas = dataJson.getJSONArray("data");
                Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
                Random random = new Random();
                datas.stream().forEach(t -> {
                    JSONObject data = (JSONObject) t;
                    SeckillGoodsDTO seckillGoodsDTO = new SeckillGoodsDTO();
                    seckillGoodsDTO.setType(1);
                    seckillGoodsDTO.setGoodsName(data.getString("itemtitle"));
                    seckillGoodsDTO.setGoodsId(data.getString("itemid"));
                    seckillGoodsDTO.setGoodsMainPicture(data.getString("itempic") + "_310x310.jpg");
                    seckillGoodsDTO.setGoodsDesc(data.getString("itemdesc"));
                    String sale = data.getString("itemsale");
                    if (!StringUtils.isEmpty(sale) && Integer.valueOf(sale) == 0){
                        sale = String.valueOf(random.nextInt(3000) + 2000);
                    }
                    seckillGoodsDTO.setSales(sale);//宝贝近2小时跑单
                    seckillGoodsDTO.setCoupon(data.getString("couponmoney"));
                    seckillGoodsDTO.setActivity_type(data.getString("activity_type"));
                    seckillGoodsDTO.setCouponUrl(data.getString("couponurl"));
                    String itemendprice = data.getString("itemendprice");
                    seckillGoodsDTO.setPriceAfterCoupon(itemendprice);
                    seckillGoodsDTO.setPrice(data.getString("itemprice"));

                    String time = Constant.Hm.format(new Date());

                    int ran = random.nextInt(6);
                    Double rate = (Double.valueOf(time) / 100 + ran) * 3.4 / 100;
                    Double num = Integer.valueOf(sale) / rate;
                    seckillGoodsDTO.setTotalNum(String.format("%.0f", num));
                    Long couponstarttime = data.getLong("couponstarttime");
                    Long couponendtime = data.getLong("couponendtime");
                    SimpleDateFormat y_m_d = Constant.y_M_d;
                    if (!StringUtils.isEmpty(couponstarttime)) {
                        String couponstart = y_m_d.format(new Date(couponstarttime));
                        seckillGoodsDTO.setCouponStartTime(couponstart);
                    }
                    if (!StringUtils.isEmpty(couponendtime)) {
                        String couponend = y_m_d.format(new Date(couponendtime));
                        seckillGoodsDTO.setCouponStartTime(couponend);
                    }

                    Double tkrates = data.getDouble("tkrates");
                    Double commission = Double.valueOf(itemendprice) * (tkrates / 100) * (reback_money);
                    seckillGoodsDTO.setCommission(String.format("%.2f", commission));


                    result.add(seckillGoodsDTO);
                });
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 参数返回(初始化)
     **/
    @Override
    public Tip stuad(StuadDTO stuadDTO, HttpServletRequest request) throws Exception {
        InitConfig config = homeMapper.selectInitConfigInfo();//获取初始化配置
        String imei = stuadDTO.getImei();
        Integer deviceT = stuadDTO.getDeviceT();
        String app_version = stuadDTO.getApp_version();
        String api_url = config.getApi_url();
        String remind_version = config.getRemind_version();//ios提示升级版本号
        if (!StringUtils.isEmpty(deviceT) && deviceT == 1){//ios
            if(!StringUtils.isEmpty(remind_version) && !StringUtils.isEmpty(app_version) && !app_version.equals(remind_version)){
                    config.setRemind_promotion(1);
                }
        }

        String url = "";
        if (!StringUtils.isEmpty(api_url)) {//随机地址
            List<String> urls = new ArrayList<>();
            JSONObject json = JSON.parseObject(api_url);
            urls.addAll(json.keySet());
            Random r = new Random();
            String s = urls.get(r.nextInt(urls.size()));
            url = json.getString(s);
        }
        config.setApi_url(url);
        SimpleDateFormat sd = Constant.y_M_d_H_m_s;
        String time = sd.format(new Date());
        Integer userId = stuadDTO.getUserId();
        if (!StringUtils.isEmpty(userId)){//更新用户最近登录时间
            User user = new User();
            user.setId(userId);
            user.setRecent_login_time(time);
            userMapper.updateById(user);
        }
        //不为空时，插入channel表
        if (!StringUtils.isEmpty(stuadDTO.getChannel_id()) && !StringUtils.isEmpty(imei)) {
            List<StuadDTO> list = homeMapper.findByIMEI(stuadDTO);
            stuadDTO.setCreate_time(time);
            SimpleDateFormat sdf = Constant.y_M_d;
            String now = sdf.format(new Date());
            if (list.size() > 0) {
                List<StuadDTO> collect = list.stream().filter(t -> now.equals(t.getCreate_time())).collect(Collectors.toList());
                if (collect.size() < 1) {
                    stuadDTO.setIs_new(0);
                    homeMapper.insertChannel(stuadDTO);
                }
            } else {
                stuadDTO.setIs_new(1);
                homeMapper.insertChannel(stuadDTO);
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), config);
    }

    /**
     * 好单库获取热搜关键词
     */
    @Override
    public Tip hotSearch() {
        Object value = jedisClient.get("htsq:hotSearch:keywords");
        List list = new ArrayList<>();
        if (null == value) {//redis数据为空时，从好单库获取热搜关键词
            String apikey = hdkPropertyConfig.getApiKey();
            String hdk_url = hdkPropertyConfig.getHotUrl() + "apikey/" + apikey;
            String dataStr = HttpConnectionPoolUtil.get(hdk_url);
            if (!StringUtils.isEmpty(dataStr)) {
                JSONObject str = JSON.parseObject(dataStr);
                JSONArray datas = str.getJSONArray("data");
                for (int i = 0; i < 20; i++) {//获取前20条
                    Object obj = datas.get(i);
                    String keyword = JSON.parseObject(JSON.toJSONString(obj)).getString("keyword");
                    list.add(keyword);
                }
                jedisClient.setWithExpire("htsq:hotSearch:keywords", JSON.toJSONString(list), 60 * 60 * 24);
            }
        } else {
            String str = JSON.toJSONString(value).replaceAll("\"", "").replaceAll("\\\\", "").replace("[", "").replace("]", "");
            String[] split = str.split(",");
            list = Arrays.asList(split);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), list);
    }

    /**
     * 商品分享链接
     **/
    @Override
    public Tip shareGoods(Integer type, String goods_id, String goods_name, Integer user_id) throws Exception {
        JSONObject json = new JSONObject();
        //类型:1淘宝 2京东 3拼多多 4唯品会
        if (!StringUtils.isEmpty(type) && type == 1) {//淘宝
            json = getTaoBaoPWD(goods_id, user_id);
        } else if (!StringUtils.isEmpty(type) && type == 2) {//2京东(京东暂无分享)

        } else if (!StringUtils.isEmpty(type) && type == 3) {//3拼多多
            Tip pddUrl = pddService.getPddUrl(String.valueOf(user_id), goods_id, "1");
            Object data = pddUrl.getData();
            if (null != data) {
                JSONObject detail = (JSONObject) JSON.parseArray(JSON.toJSONString(data)).get(0);
                String goodsUrl = detail.getString("mobile_short_url");
                String command = "【" + goods_name + "】" + goodsUrl + "点击链接，再选择浏览器打开；或复制这条信息，打开手机拼多多";
                json.put("result", command);
                json.put("url", goodsUrl);
            }
        } else if (!StringUtils.isEmpty(type) && type == 4) {
            Object ob = wphService.wphGenerateLink(user_id, goods_id, 1).getData();
            json = (JSONObject) ob;
        }
        if(StringUtils.isEmpty(json)){
            return ResultUtil.result(BizExceptionEnum.GOODS_INFO_IS_NULL.getCode(), BizExceptionEnum.GOODS_INFO_IS_NULL.getMessage());
        }
        json.put("desc", "点击打开购买链接");
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), json);
    }

    /**
     * 跳转时需转换的链接
     **/
    @Override
    public Tip exchangeUrl(Integer discern_id, Integer user_id,String theme_id) throws Exception {
        if (StringUtils.isEmpty(discern_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        Tip tip = new Tip();
        if (discern_id == 7) {//拼多多每日红包
            tip = pddService.pddRedpacket(String.valueOf(user_id));
        }else if (discern_id == 11){//拼多多主题推广
            tip = pddService.pddThemeUrl(String.valueOf(user_id), Long.valueOf(theme_id));
        }
        return tip;
    }

    /**
     * 获取视频教程链接
     **/
    @Override
    public Tip course() {
        List<ImageConfig> list = homeMapper.getCourse();
        JSONObject result = new JSONObject();
        list.stream().forEach(t -> {
            Integer type = t.getType();
            String file = t.getFile();
            if (type == 3) {//视频教程
                result.put("video_url", file);
            } else if (type == 4) {//第一帧图片
                result.put("pic_url", file);
            }
        });
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 零元购商品列表
     **/
    @Override
    public Tip zeroList(Integer user_id,String token_id,Integer pageNum) throws Exception{
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(token_id)){
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        Page page = new Page(pageNum,Constant.PAGE_SIZE_20);
        List<ZeroPurchaseDTO> result = homeMapper.selectZeroList(page);
        result.stream().forEach(t -> {
            String coupon_endTime = t.getCoupon_endTime();
            if(!StringUtils.isEmpty(coupon_endTime)){
                try {
                    Date date = DateFormat.getDateInstance().parse(coupon_endTime);
                    Date now = new Date();
                    if (date.getTime() <= now.getTime()){//当券结束时间小于等于现在时间时，把券价格设置为0
                        t.setPrice_coupons("0");
                        t.setIfcoupon(0);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
        page.setRecords(result);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), page);
    }

    /**
     * 获取淘口令
     *
     * @return
     */
    private JSONObject getTaoBaoPWD(String goodsId, Integer user_id) throws Exception {
        String url = tblmPropertyConfig.getUrl();
        String appkey = tblmPropertyConfig.getAppKey();
        String secret = tblmPropertyConfig.getAppSecret();
        JSONObject result = new JSONObject();
        //通过商品id获取淘宝商品详情
        String strData = tbGoodsService.getGoodsDetail(goodsId);

        if (!StringUtils.isEmpty(strData)) {
            JSONObject data = JSONObject.parseObject(strData);
            JSONObject detail = data.getJSONObject("data");
            String itempic = detail.getString("itempic");//图片
            String itemtitle = detail.getString("itemtitle");//商品名称
            String couponmoney = detail.getString("couponmoney");//券额
            String price=detail.getString("itemprice");//原价
            String itemendprice=detail.getString("itemendprice");//券后价
            Boolean ifCoupon = false;
            if (!StringUtils.isEmpty(couponmoney) && Double.valueOf(couponmoney) > 0) {
                ifCoupon = true;
            }
            //获取购买url
            Tip tip = tbGoodsService.goodsInfo(goodsId, String.valueOf(user_id), "", ifCoupon, "1", "1.1.1", "0");
            if(tip.getCode() != 200){
                return null;
            }
            Object obj = tip.getData();
            JSONObject jsonObj = JSON.parseObject(JSON.toJSONString(obj));
            String buyUrl = jsonObj.getString("url");

            TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
            //转换为短链接
            TbkSpreadGetRequest req = new TbkSpreadGetRequest();
            List<TbkSpreadGetRequest.TbkSpreadRequest> list2 = new ArrayList<>();
            TbkSpreadGetRequest.TbkSpreadRequest spreadRequest = new TbkSpreadGetRequest.TbkSpreadRequest();
            spreadRequest.setUrl(buyUrl);
            list2.add(spreadRequest);
            req.setRequests(list2);
            TbkSpreadGetResponse response = client.execute(req);
            String shortUrl = response.getResults().get(0).getContent();

            TbkTpwdCreateRequest createRequest = new TbkTpwdCreateRequest();
            createRequest.setText(itemtitle);
            createRequest.setUrl(buyUrl);
            createRequest.setLogo(itempic);
            TbkTpwdCreateResponse rsp = client.execute(createRequest);
            String body = rsp.getBody();
            JSONObject tpwd = JSON.parseObject(body);
            String model = tpwd.getJSONObject("tbk_tpwd_create_response").getJSONObject("data").getString("model");
            model=model.substring(1);
            model=model.substring(0,model.length()-1);
            if (!StringUtils.isEmpty(shortUrl)) {
                buyUrl = shortUrl;
            }
            String str ="";
            if(ifCoupon){
                str =  itemtitle + "\uD83D\uDC47\uD83D\uDC47\uD83D\uDC47" + System.lineSeparator() + "【在售价】￥" + price+System.lineSeparator()
                        +"【券后价】￥"+itemendprice+System.lineSeparator()
                        +"---------\uD83C\uDF51--------"+System.lineSeparator()+"覆制这段内容("+model+") 咑tao宝即可领券✅";
            }else{
                str =  itemtitle + "\uD83D\uDC47\uD83D\uDC47\uD83D\uDC47" +  System.lineSeparator() + "【在售价】￥" + price+ System.lineSeparator()

                        +"--------\uD83C\uDF51---------"+ System.lineSeparator()+"覆制这段内容("+model+")咑开tao宝即可✅";
            }
            result.put("result", str);
            result.put("url", buyUrl);
        }
        return result;
    }

    /**
     * 分类
     **/
    @Override
    public Tip stulist() throws Exception {
        JSONObject result = new JSONObject();
        JSONArray mylist = new JSONArray();

        JSONObject mylist1 = new JSONObject(true);
        List<String> chlist1 = new ArrayList<>();
        List<String> urllist1 = new ArrayList<>();

        JSONObject mylist2 = new JSONObject(true);
        List<String> chlist2 = new ArrayList<>();
        List<String> urllist2 = new ArrayList<>();

        JSONObject mylist3 = new JSONObject(true);
        List<String> chlist3 = new ArrayList<>();
        List<String> urllist3 = new ArrayList<>();

        JSONObject mylist4 = new JSONObject(true);
        List<String> chlist4 = new ArrayList<>();
        List<String> urllist4 = new ArrayList<>();

        JSONObject mylist5 = new JSONObject(true);
        List<String> chlist5 = new ArrayList<>();
        List<String> urllist5 = new ArrayList<>();

        JSONObject mylist6 = new JSONObject(true);
        List<String> chlist6 = new ArrayList<>();
        List<String> urllist6 = new ArrayList<>();

        JSONObject mylist7 = new JSONObject(true);
        List<String> chlist7 = new ArrayList<>();
        List<String> urllist7 = new ArrayList<>();

        JSONObject mylist8 = new JSONObject(true);
        List<String> chlist8 = new ArrayList<>();
        List<String> urllist8 = new ArrayList<>();

        JSONObject mylist9 = new JSONObject(true);
        List<String> chlist9 = new ArrayList<>();
        List<String> urllist9 = new ArrayList<>();

        JSONObject mylist10 = new JSONObject(true);
        List<String> chlist10 = new ArrayList<>();
        List<String> urllist10 = new ArrayList<>();

        JSONObject mylist11 = new JSONObject(true);
        List<String> chlist11 = new ArrayList<>();
        List<String> urllist11 = new ArrayList<>();

        JSONObject mylist12 = new JSONObject(true);
        List<String> chlist12 = new ArrayList<>();
        List<String> urllist12 = new ArrayList<>();

        JSONObject mylist13 = new JSONObject(true);
        List<String> chlist13 = new ArrayList<>();
        List<String> urllist13 = new ArrayList<>();

        JSONObject mylist14 = new JSONObject(true);
        List<String> chlist14 = new ArrayList<>();
        List<String> urllist14 = new ArrayList<>();

        JSONObject mylist15 = new JSONObject(true);
        List<String> chlist15 = new ArrayList<>();
        List<String> urllist15 = new ArrayList<>();

        JSONObject mylist16 = new JSONObject(true);
        List<String> chlist16 = new ArrayList<>();
        List<String> urllist16 = new ArrayList<>();

        JSONObject mylist17 = new JSONObject(true);
        List<String> chlist17 = new ArrayList<>();
        List<String> urllist17 = new ArrayList<>();

        JSONObject mylist18 = new JSONObject(true);
        List<String> chlist18 = new ArrayList<>();
        List<String> urllist18 = new ArrayList<>();

        JSONObject mylist19 = new JSONObject(true);
        List<String> chlist19 = new ArrayList<>();
        List<String> urllist19 = new ArrayList<>();

        chlist1.add("婴童服饰");
        chlist1.add("玩具书籍");
        chlist1.add("婴童寝居");
        chlist1.add("婴童洗护");
        chlist1.add("喂养用品");
        chlist1.add("出行产品");
        chlist1.add("孕产用品");
        chlist1.add("尿不湿");
        chlist1.add("婴童湿巾");
        chlist1.add("妈咪包背婴带");
        chlist1.add("安全座椅");
        chlist1.add("童桌童床");
        urllist1.add("https://meimg.su.bcebos.com/img/1.jpg");
        urllist1.add("https://meimg.su.bcebos.com/img/2.png");
        urllist1.add("https://meimg.su.bcebos.com/img/3.jpg");
        urllist1.add("https://meimg.su.bcebos.com/img/4.png");
        urllist1.add("https://meimg.su.bcebos.com/img/5.jpg");
        urllist1.add("https://meimg.su.bcebos.com/img/6.jpg");
        urllist1.add("https://meimg.su.bcebos.com/img/7.jpg");
        urllist1.add("https://meimg.su.bcebos.com/img/8.jpg");
        urllist1.add("https://meimg.su.bcebos.com/img/9.jpg");
        urllist1.add("https://meimg.su.bcebos.com/img/10.png");
        urllist1.add("https://meimg.su.bcebos.com/img/11.png");
        urllist1.add("https://meimg.su.bcebos.com/img/12.png");
        mylist1.put("name", "母婴");
        mylist1.put("chlist", chlist1);
        mylist1.put("urllist", urllist1);

        chlist2.add("谷物冲饮");
        chlist2.add("休闲零食");
        chlist2.add("精选肉食");
        chlist2.add("坚果蜜饯");
        chlist2.add("糕点饼干");
        chlist2.add("水果蔬菜");
        chlist2.add("保健滋补");
        chlist2.add("河海生鲜");
        chlist2.add("茶酒冲饮");
        chlist2.add("粮油调味");
        urllist2.add("https://meimg.su.bcebos.com/img/13.png");
        urllist2.add("https://meimg.su.bcebos.com/img/14.png");
        urllist2.add("https://meimg.su.bcebos.com/img/15.png");
        urllist2.add("https://meimg.su.bcebos.com/img/16.png");
        urllist2.add("https://meimg.su.bcebos.com/img/17.png");
        urllist2.add("https://meimg.su.bcebos.com/img/18.png");
        urllist2.add("https://meimg.su.bcebos.com/img/19.jpg");
        urllist2.add("https://meimg.su.bcebos.com/img/20.png");
        urllist2.add("https://meimg.su.bcebos.com/img/21.png");
        urllist2.add("https://meimg.su.bcebos.com/img/22.png");
        mylist2.put("name", "食品");
        mylist2.put("chlist", chlist2);
        mylist2.put("urllist", urllist2);

        chlist3.add("高跟鞋");
        chlist3.add("运动鞋");
        chlist3.add("靴子");
        chlist3.add("帆布鞋");
        chlist3.add("低帮鞋");
        chlist3.add("雨鞋");
        chlist3.add("高帮鞋");
        chlist3.add("凉鞋");
        chlist3.add("拖鞋");
        for (int i = 23; i <= 31; i++) {
            urllist3.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist3.put("name", "女鞋");
        mylist3.put("chlist", chlist3);
        mylist3.put("urllist", urllist3);

        chlist4.add("连衣裙");
        chlist4.add("毛针织衫");
        chlist4.add("风衣");
        chlist4.add("套装");
        chlist4.add("棉衣棉服");
        chlist4.add("毛呢外套");
        chlist4.add("羽绒服");
        chlist4.add("大码女装");
        chlist4.add("裤子");
        chlist4.add("礼服");
        chlist4.add("西装裤");
        chlist4.add("打底裤");
        chlist4.add("棉裤羽绒裤");
        chlist4.add("职业装");
        chlist4.add("毛衣");
        chlist4.add("蕾丝雪纺衫");
        chlist4.add("上衣");
        chlist4.add("背心吊带");
        chlist4.add("妈妈装");
        chlist4.add("皮衣");
        chlist4.add("西装");
        chlist4.add("外套");
        chlist4.add("衬衣");
        chlist4.add("半身裙");
        chlist4.add("牛仔裤");
        chlist4.add("休闲裤");
        chlist4.add("T恤");
        for (int i = 32; i <= 58; i++) {
            urllist4.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist4.put("name", "女装");
        mylist4.put("chlist", chlist4);
        mylist4.put("urllist", urllist4);

        chlist5.add("彩妆");
        chlist5.add("美妆工具");
        chlist5.add("香水");
        chlist5.add("男士护肤");
        for (int i = 59; i <= 62; i++) {
            urllist5.add("https://meimg.su.bcebos.com/img/" + i + ".jpg");
        }
        mylist5.put("name", "彩妆");
        mylist5.put("chlist", chlist5);
        mylist5.put("urllist", urllist5);

        chlist6.add("家庭清洁");
        chlist6.add("洗发造型");
        chlist6.add("个人护理");
        chlist6.add("纸品湿巾");
        chlist6.add("口腔护理");
        chlist6.add("美容护肤");
        chlist6.add("洗浴用品");
        chlist6.add("女性护理");
        chlist6.add("衣物清洁");
        chlist6.add("驱蚊杀虫");
        chlist6.add("身体护理");
        chlist6.add("男士个护");
        for (int i = 63; i <= 74; i++) {
            urllist6.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist6.put("name", "洗护");
        mylist6.put("chlist", chlist6);
        mylist6.put("urllist", urllist6);

        chlist7.add("运动鞋服");
        chlist7.add("游泳");
        chlist7.add("骑行装备");
        chlist7.add("运动配件");
        chlist7.add("瑜伽");
        chlist7.add("泳衣");
        chlist7.add("户外鞋服");
        chlist7.add("户外装备");
        chlist7.add("运动工具");
        for (int i = 75; i <= 83; i++) {
            urllist7.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist7.put("name", "运动");
        mylist7.put("chlist", chlist7);
        mylist7.put("urllist", urllist7);

        chlist8.add("旅行箱包");
        chlist8.add("女包");
        chlist8.add("双肩包");
        chlist8.add("钱包");
        chlist8.add("男包");
        chlist8.add("功能包");
        chlist8.add("箱包配件");
        for (int i = 84; i <= 90; i++) {
            urllist8.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist8.put("name", "箱包");
        mylist8.put("chlist", chlist8);
        mylist8.put("urllist", urllist8);

        chlist9.add("文胸");
        chlist9.add("内裤");
        chlist9.add("袜子");
        chlist9.add("睡衣家居服");
        chlist9.add("文胸套装");
        chlist9.add("塑身衣");
        chlist9.add("背心T恤");
        chlist9.add("保暖内衣");
        chlist9.add("文胸配件");
        for (int i = 91; i <= 99; i++) {
            urllist9.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist9.put("name", "内衣");
        mylist9.put("chlist", chlist9);
        mylist9.put("urllist", urllist9);

        chlist10.add("音像制品");
        chlist10.add("驱蚊灭虫");
        chlist10.add("学生文具");
        chlist10.add("居家用品");
        chlist10.add("日用百货");
        chlist10.add("办公用品");
        chlist10.add("图书阅读");
        chlist10.add("毛巾浴巾");
        chlist10.add("收纳储物");
        chlist10.add("绿植园艺");
        chlist10.add("汽车用品");
        chlist10.add("桌游棋牌");
        chlist10.add("人偶娃娃");
        chlist10.add("模型手办");
        chlist10.add("美术兴趣");
        chlist10.add("毛笔相关");
        chlist10.add("洛丽塔");
        chlist10.add("乐器配件");
        chlist10.add("乐器");
        chlist10.add("教学用具");
        chlist10.add("户外广告");
        chlist10.add("古风外衣");
        chlist10.add("动漫影视周边");
        chlist10.add("点读机");
        chlist10.add("办公桌椅");
        chlist10.add("COS专区");
        chlist10.add("展柜货架");
        for (int i = 100; i <= 126; i++) {
            urllist10.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist10.put("name", "百货");
        mylist10.put("chlist", chlist10);
        mylist10.put("urllist", urllist10);

        chlist11.add("音响音箱");
        chlist11.add("大家电");
        chlist11.add("厨房大电");
        chlist11.add("生活电器");
        chlist11.add("商用电器");
        chlist11.add("家庭影音");
        chlist11.add("耳机配件");
        chlist11.add("厨房电器");
        for (int i = 127; i <= 134; i++) {
            urllist11.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist11.put("name", "家电");
        mylist11.put("chlist", chlist11);
        mylist11.put("urllist", urllist11);

        chlist12.add("床上用品");
        chlist12.add("餐具");
        chlist12.add("家具");
        chlist12.add("厨房用具");
        chlist12.add("家装");
        chlist12.add("厨房工具");
        chlist12.add("储物收纳");
        chlist12.add("灯饰光源");
        chlist12.add("装修建材");
        chlist12.add("装饰");
        chlist12.add("保温杯");
        chlist12.add("酒具");
        chlist12.add("茶具");
        chlist12.add("一次性用品");
        chlist12.add("咖啡相关");
        chlist12.add("饭盒");
        chlist12.add("杯类");
        chlist12.add("烧烤野炊");
        chlist12.add("烘焙");
        chlist12.add("机电五金");
        chlist12.add("工具");
        chlist12.add("测量仪器");
        chlist12.add("电子原件");
        chlist12.add("开关插座");
        chlist12.add("电路线材");
        chlist12.add("安防监控");
        chlist12.add("艺术品");
        for (int i = 135; i <= 161; i++) {
            urllist12.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist12.put("name", "家居");
        mylist12.put("chlist", chlist12);
        mylist12.put("urllist", urllist12);

        chlist13.add("计生用品");
        chlist13.add("避孕套");
        chlist13.add("情爱玩具");
        chlist13.add("情趣内衣");
        chlist13.add("女用玩具");
        for (int i = 162; i <= 166; i++) {
            urllist13.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist13.put("name", "成人");
        mylist13.put("chlist", chlist13);
        mylist13.put("urllist", urllist13);

        chlist14.add("手机");
        chlist14.add("游戏机");
        chlist14.add("移动电源");
        chlist14.add("相机");
        chlist14.add("台式电脑");
        chlist14.add("手机配件");
        chlist14.add("平板电脑");
        chlist14.add("品牌电脑");
        chlist14.add("笔记本");
        chlist14.add("路由器");
        chlist14.add("镜头");
        chlist14.add("电脑外设");
        chlist14.add("移动硬盘");
        chlist14.add("摄像机");
        chlist14.add("内存卡");
        chlist14.add("交换机");
        chlist14.add("耳机");
        chlist14.add("读卡器");
        chlist14.add("电脑硬件");
        chlist14.add("充电电池");
        chlist14.add("U盘");
        chlist14.add("MP3");
        chlist14.add("学习工具");
        chlist14.add("相机配件");
        for (int i = 167; i <= 190; i++) {
            urllist14.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist14.put("name", "数码");
        mylist14.put("chlist", chlist14);
        mylist14.put("urllist", urllist14);

        chlist15.add("面部护肤");
        chlist15.add("男士护肤");
        chlist15.add("身体护理");
        chlist15.add("T区护理");
        for (int i = 191; i <= 194; i++) {
            urllist15.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist15.put("name", "护肤");
        mylist15.put("chlist", chlist15);
        mylist15.put("urllist", urllist15);

        chlist16.add("爸爸装");
        chlist16.add("短裤中裤");
        chlist16.add("卫衣");
        chlist16.add("背心马甲");
        chlist16.add("套装");
        chlist16.add("POLO衫");
        chlist16.add("衬衫");
        chlist16.add("牛仔裤");
        chlist16.add("休闲裤");
        chlist16.add("T恤");
        chlist16.add("皮裤");
        chlist16.add("针织衫毛衣");
        chlist16.add("职业装");
        chlist16.add("皮衣");
        chlist16.add("毛呢大衣");
        chlist16.add("棉衣");
        chlist16.add("羽绒服");
        chlist16.add("风衣");
        chlist16.add("夹克");
        chlist16.add("棉裤");
        for (int i = 195; i <= 214; i++) {
            urllist16.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist16.put("name", "男装");
        mylist16.put("chlist", chlist16);
        mylist16.put("urllist", urllist16);

        chlist17.add("萌猫");
        chlist17.add("萌狗");
        chlist17.add("鱼水族");
        chlist17.add("鸟");
        chlist17.add("宠物美容");
        chlist17.add("宠物清洁");
        chlist17.add("护理保健");
        chlist17.add("食具食品");
        chlist17.add("玩具");
        chlist17.add("兔");
        chlist17.add("豚鼠");
        chlist17.add("宠物窝");
        chlist17.add("飞鼠");
        chlist17.add("仓鼠");
        chlist17.add("香猪");
        chlist17.add("龟");
        for (int i = 215; i <= 230; i++) {
            urllist17.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist17.put("name", "萌宠");
        mylist17.put("chlist", chlist17);
        mylist17.put("urllist", urllist17);

        chlist18.add("手表");
        chlist18.add("贵重饰品");
        chlist18.add("时尚饰品");
        chlist18.add("眼镜");
        chlist18.add("烟具");
        chlist18.add("瑞士军刀");
        for (int i = 231; i <= 236; i++) {
            urllist18.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist18.put("name", "配饰");
        mylist18.put("chlist", chlist18);
        mylist18.put("urllist", urllist18);

        chlist19.add("布鞋");
        chlist19.add("商务休闲");
        chlist19.add("正装鞋");
        chlist19.add("休闲鞋");
        chlist19.add("靴子");
        chlist19.add("高帮鞋");
        chlist19.add("拖鞋");
        chlist19.add("凉鞋");
        chlist19.add("帆布鞋");
        chlist19.add("低帮鞋");
        chlist19.add("增高鞋");
        chlist19.add("雨鞋");
        urllist19.add("https://meimg.su.bcebos.com/img/237.png");
        urllist19.add("https://meimg.su.bcebos.com/img/238.jpg");
        for (int i = 239; i <= 248; i++) {
            urllist19.add("https://meimg.su.bcebos.com/img/" + i + ".png");
        }
        mylist19.put("name", "男鞋");
        mylist19.put("chlist", chlist19);
        mylist19.put("urllist", urllist19);

        mylist.add(mylist1);
        mylist.add(mylist2);
        mylist.add(mylist3);
        mylist.add(mylist4);
        mylist.add(mylist5);
        mylist.add(mylist6);
        mylist.add(mylist7);
        mylist.add(mylist8);
        mylist.add(mylist9);
        mylist.add(mylist10);
        mylist.add(mylist11);
        mylist.add(mylist12);
        mylist.add(mylist13);
        mylist.add(mylist14);
        mylist.add(mylist15);
        mylist.add(mylist16);
        mylist.add(mylist17);
        mylist.add(mylist18);
        mylist.add(mylist19);
        result.put("mylist", mylist);

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }
}
